/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.epam.expertsys;

import org.apache.log4j.Logger;
import java.util.ArrayList;
import java.io.*;

/**
 *
 * @author Admin
 */
public class RulesKnown {

    private static Logger log = Logger.getLogger(RulesKnown.class);
    private static RulesKnown instance;
    private ArrayList<Rule> Rules;
    private int numberRulesInList;

    public void addRule(Rule newRule) {
        this.Rules.add(newRule);
        this.numberRulesInList++;
    }

    public Rule getRule(int index) {
        return this.Rules.get(index);
    }

    public int getNumberRules() {
        return this.numberRulesInList;
    }

    private RulesKnown() {
        Rules = new ArrayList<Rule>();
        numberRulesInList = 0;
    }

    public static RulesKnown getInstance() {
        if (instance == null) {
            instance = new RulesKnown();
        }
        return instance;
    }

    public void readRulesFile(String fileName) {
        try {
            FileReader fileReader = new FileReader(fileName);
            BufferedReader bufReader = new BufferedReader(fileReader);
            int numNewRules = Integer.parseInt(bufReader.readLine());
            String bufName;
            String bufVal;
            ArrayList<Fact> ruleConditions = new ArrayList<Fact>();

            for (int counter = 0; counter < numNewRules; counter++) {

                int numConditions = Integer.parseInt(bufReader.readLine());
                System.out.println("NumCond=" + numConditions);
                for (int inCount = 0; inCount < numConditions; inCount++) {
                    bufName = bufReader.readLine();
                    bufVal = bufReader.readLine();
                    Fact tmp = Fact.create(bufName, bufVal);
                    ruleConditions.add(tmp);
                }
                bufName = bufReader.readLine();
                bufVal = bufReader.readLine();
                Rule newRule = Rule.create(ruleConditions,
                        Fact.create(bufName, bufVal));
                this.addRule(newRule);
                ruleConditions.clear();
                System.out.println("Iter = " + counter);
                System.out.println("nfacts = " + newRule.numConditions());
                System.out.println("Cond = " + newRule.getConsequence().getVarName());
                //bufReader.
            }
        } catch (FileNotFoundException e) {
            log.error("File " + fileName + " not found");
        } catch (IOException e) {
            log.error("File " + fileName + " closed");
        } catch (VariableRedefinedException e) {
            log.error("Attempt to override variable; "
                    + "reading terminated");
        } catch (NullValueException e) {
            log.error("File corrupted; reading terminated");
        } catch (RepeatedConditionException e) {
            log.error("Repeated condition");
        }
    }
}
